package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String iss = "Authorization Server";
    private static final String secretKey = "MyRandomlyGeneratedSecretKeyForJwt";
    private static final SecretKey key = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));

    /**
     * 创建JWT
     * 头部 + 负载 + 签名
     * <a href="https://jwt.io/introduction">JWT Introduction</a>
     */
    public static String createJwt(Map<String, String> claims) {
        // 注册声明 Registered Claims: iss, exp, iat
        // 私有声明 Private Claims: userAccount
        JwtBuilder jwtBuilder = Jwts.builder()
                .issuer(iss)
                .expiration(new Date(System.currentTimeMillis() + 1000 * 60 * 5))
                .issuedAt(new Date())
                .claims(claims)
                .signWith(key);

        // 如何生成JWT？
        // HMACSHA256(base64UrlEncode({"alg":"HS256"}) + "." +
        // base64UrlEncode({"iss":"Authorization Server","exp":1736839924,"iat":1736839624,"userAccount":"chenquanchi"}) + "." +
        // my-256-bit-secret)
        return jwtBuilder.compact();
    }

    /**
     * 解析JWT
     */
    public static String parseJwt(String jwt) {
        Jws<Claims> claimsJws = Jwts.parser().verifyWith(key).build().parseSignedClaims(jwt);
        Claims payload = claimsJws.getPayload();
        if (payload.get("userAccount") != null)
            return payload.get("userAccount").toString();
        else
            return null;
    }
}
